package com.zdsoft.wms.filter;


import com.zdsoft.wms.utils.CookieUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Component;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletRequestWrapper;
import java.io.IOException;
@WebFilter(urlPatterns = "/*", filterName = "Filter")
@Component
@Slf4j
public class TokenFilter implements Filter {

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequestWrapper wrapper=new HttpServletRequestWrapper((HttpServletRequest) servletRequest){

            @Override
            public String getHeader(String name) {
                String superHeader = super.getHeader(name);
                if ("X-Token".equals(name)&&StringUtils.isEmpty(superHeader)){
                    return  CookieUtil.readLoginToken((HttpServletRequest) servletRequest);
                }
                return super.getHeader(name);
            }
        };



    log.info("--------------------filter-------------------");
//        HttpServletRequest request = (HttpServletRequest) servletRequest;
//        String token= (String) request.getAttribute("X-Token");
//        if (StringUtils.isEmpty(token)){
//            String loginToken = CookieUtil.readLoginToken(request);
//            if (StringUtils.isNotEmpty(loginToken)){
//                request.setAttribute("X-Token",loginToken);
//                log.info("--------------------token-------------------");
//            }
//        }
        filterChain.doFilter(wrapper,servletResponse);
    }

    @Override
    public void destroy() {

    }
}
